{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "\n",
    "import cv2\n",
    "import numpy as np\n",
    "import torch\n",
    "import torchvision\n",
    "\n",
    "from boxmot import BotSort\n",
    "\n",
    "# Load a pre-trained Faster R-CNN model\n",
    "device = torch.device('cpu')  # Use 'cuda' if you have a GPU\n",
    "detector = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)\n",
    "detector.eval().to(device)\n",
    "\n",
    "# Initialize the tracker\n",
    "tracker = BotSort(\n",
    "    reid_weights=Path('osnet_x0_25_msmt17.pt'),  # Path to ReID model\n",
    "    device=device,  # Use CPU for inference\n",
    "    half=False\n",
    ")\n",
    "\n",
    "# Open the video file\n",
    "vid = cv2.VideoCapture(0)  # or 'path/to/your.avi\n",
    "\n",
    "while True:\n",
    "    # Capture frame-by-frame\n",
    "    ret, frame = vid.read()\n",
    "\n",
    "    # If ret is False, it means we have reached the end of the video\n",
    "    if not ret:\n",
    "        break\n",
    "\n",
    "    # Convert frame to tensor and move to device\n",
    "    frame_tensor = torchvision.transforms.functional.to_tensor(frame).to(device)\n",
    "\n",
    "    # Perform detection\n",
    "    with torch.no_grad():\n",
    "        detections = detector([frame_tensor])[0]\n",
    "\n",
    "    # Filter the detections (e.g., based on confidence threshold)\n",
    "    confidence_threshold = 0.5\n",
    "    dets = []\n",
    "    for i, score in enumerate(detections['scores']):\n",
    "        if score >= confidence_threshold:\n",
    "            bbox = detections['boxes'][i].cpu().numpy()\n",
    "            label = detections['labels'][i].item()\n",
    "            conf = score.item()\n",
    "            dets.append([*bbox, conf, label])\n",
    "\n",
    "    # Convert detections to numpy array (N X (x, y, x, y, conf, cls))\n",
    "    dets = np.array(dets)\n",
    "\n",
    "    # Update the tracker\n",
    "    res = tracker.update(dets, frame)  # --> M X (x, y, x, y, id, conf, cls, ind)\n",
    "\n",
    "    # Plot tracking results on the image\n",
    "    tracker.plot_results(frame, show_trajectories=True)\n",
    "    \n",
    "    cv2.imshow('BoXMOT + Torchvision', frame)\n",
    "\n",
    "    # Simulate wait for key press to continue, press 'q' to exit\n",
    "    key = cv2.waitKey(1) & 0xFF\n",
    "    if key == ord('q'):\n",
    "        break\n",
    "\n",
    "# Release resources\n",
    "vid.release()\n",
    "cv2.destroyAllWindows()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "boxmot-YDNZdsaB-py3.11",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
